package com.bobbygu.libnet.baserx;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bobbygu.libnet.exception.ServerException;
import com.bobbygu.libnet.utils.DeviceUtil;

import io.reactivex.subscribers.ResourceSubscriber;

/**
 * des:订阅封装
 * Created by xsf
 * on 2016.09.10:16
 */

/********************
 * 使用例子
 ********************/
/*_apiService.login(mobile, verifyCode)
        .//省略
        .subscribe(new RxSubscriber<User user>(mContext,false) {
@Override
public void _onNext(User user) {
        // 处理user
        }

@Override
public void _onError(String msg) {
        ToastUtil.showShort(mActivity, msg);
        });*/
public abstract class RxSubscriber<T> extends ResourceSubscriber<T> {

    private Context mContext;
    private String msg;

    public RxSubscriber(Context context, String msg, boolean showDialog) {
        this.mContext = context;
        this.msg = msg;
    }

    public RxSubscriber(Context context) {
        this(context, "is_downing", true);
    }

    public RxSubscriber(Context context, boolean showDialog) {
        this(context, "is_downing", showDialog);
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    public void onNext(T t) {
        _onNext(t);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        //网络
        if ("".equals(DeviceUtil.getNetWork(mContext))) {
            _onError("TIP_NO_NETWORK");
        }
        //服务器
        else if (e instanceof ServerException) {
            _onError(e.getMessage());
        }
        //其它
        else {
            JSONArray jsonArray = JSON.parseArray(e.getMessage());
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            String _exceptionMessage = jsonObject.getString("_exceptionMessage");
            String _exceptionMessageCode = jsonObject.getString("_exceptionMessageCode");
//            _onError(BaseApplication.getAppContext().getString(R.string.net_error));
            _onError(_exceptionMessage);
        }
    }

    protected abstract void _onNext(T t);

    protected abstract void _onError(String message);

}
